package qq2564874169.tuaotuao.fx.orm.mybatis;

import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.session.Configuration;
import org.w3c.dom.Element;
import qq2564874169.tuaotuao.fx.FxXml;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class MyConfiguration extends Configuration {
    private Map<String, Integer> msHashCode = new ConcurrentHashMap<>();
    private List<String> passlist = new ArrayList<>();

    public MyConfiguration(Environment environment) {
        super(environment);
    }

    @Override
    public void addMappedStatement(MappedStatement ms) {
        if (passlist.contains(ms.getId())) {
            return;
        }
        if (hasStatement(ms.getId())) {
            mappedStatements.remove(ms.getId());
        }
        super.addMappedStatement(ms);
    }

    public void addAfter() {
        passlist.clear();
    }

    public void addBefore(String path) {
        String ns;
        List<Element> els;
        try (FxXml xml = new FxXml(path)) {
            Element mapper = xml.first("/mapper");
            ns = mapper.getAttribute("namespace");
            els = xml.find("/mapper/select|update|insert|delete");
        }
        for (Element e : els) {
            String sql = FxXml.outerXML(e);
            int code = sql.hashCode();
            String id = ns + "." + e.getAttribute("id");
            if (hasStatement(id)) {
                if (msHashCode.get(id).equals(code)) {
                    passlist.add(id);
                }
            }
            msHashCode.put(id, code);
        }
    }
}
